<template>
  <div id="app">
    <header>
      <div class="header-container">
        <div class="logo">
          <router-link to="/">
            <span class="logo-icon">+</span>
            <span class="logo-text">医疗众包平台</span>
          </router-link>
        </div>
        <nav>
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/history" class="nav-link">历史记录</router-link>
          <router-link to="/statistics" class="nav-link">统计分析</router-link>
          <router-link to="/login" v-if="!isLoggedIn" class="nav-link">登录</router-link>
          <router-link to="/register" v-if="!isLoggedIn" class="nav-link">注册</router-link>
          <template v-if="isLoggedIn">
            <router-link v-if="isResearcher" to="/researcher-projects" class="nav-link">我的项目</router-link>
            <router-link v-else to="/participant-projects" class="nav-link">项目参与</router-link>
            <router-link v-if="isResearcher" to="/create-project" class="nav-link create-project-link">
              <i class="el-icon-plus"></i> 创建项目
            </router-link>
            <div class="user-identity">
              <span class="user-avatar">{{ userInitial }}</span>
              <div class="user-details">
                <span class="user-name">{{ userName }}</span>
                <span class="user-role" :class="userRoleClass">
                  <i class="el-icon-user"></i> {{ userRoleText }}
                </span>
              </div>
            </div>
            <a href="#" @click.prevent="logout" class="nav-link logout-link">退出登录</a>
          </template>
        </nav>
        <div class="mobile-menu-toggle" @click="toggleMobileMenu">
          <div class="bar"></div>
          <div class="bar"></div>
          <div class="bar"></div>
        </div>
        <div class="mobile-menu" :class="{ 'active': mobileMenuActive }">
          <router-link to="/" class="mobile-nav-link" @click="closeMobileMenu">首页</router-link>
          <router-link to="/history" class="mobile-nav-link" @click="closeMobileMenu">历史记录</router-link>
          <router-link to="/statistics" class="mobile-nav-link" @click="closeMobileMenu">统计分析</router-link>
          <router-link to="/login" v-if="!isLoggedIn" class="mobile-nav-link" @click="closeMobileMenu">登录</router-link>
          <router-link to="/register" v-if="!isLoggedIn" class="mobile-nav-link" @click="closeMobileMenu">注册</router-link>
          <template v-if="isLoggedIn">
            <router-link v-if="isResearcher" to="/researcher-projects" class="mobile-nav-link" @click="closeMobileMenu">我的项目</router-link>
            <router-link v-else to="/participant-projects" class="mobile-nav-link" @click="closeMobileMenu">项目参与</router-link>
            <router-link v-if="isResearcher" to="/create-project" class="mobile-nav-link" @click="closeMobileMenu">创建项目</router-link>
            <div class="mobile-user-identity" @click="closeMobileMenu">
              <span class="user-avatar">{{ userInitial }}</span>
              <div class="user-details">
                <span class="user-name">{{ userName }}</span>
                <span class="user-role" :class="userRoleClass">
                  <i class="el-icon-user"></i> {{ userRoleText }}
                </span>
              </div>
            </div>
            <a href="#" @click.prevent="logout" class="mobile-nav-link logout-link">登出</a>
          </template>
        </div>
      </div>
    </header>
    <main>
      <router-view/>
    </main>
    <footer>
      <p>&copy; 2025 医疗众包平台</p>
    </footer>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      mobileMenuActive: false,
      userDataLoaded: false
    }
  },
  created() {
    console.log('App创建，开始初始化用户数据');
    this.initUserData();
  },
  mounted() {
    // 页面加载后，再次尝试获取用户信息
    console.log('App挂载完成，检查用户身份');
    setTimeout(() => {
      // 延迟执行，确保store已完全初始化
      if (this.isLoggedIn) {
        console.log('检测到用户已登录，角色状态:', {
          isResearcher: this.isResearcher,
          user: this.currentUser
        });
        
        // 检查是否有登录后的重定向目标
        const redirectTarget = localStorage.getItem('loginRedirect');
        if (redirectTarget) {
          console.log('检测到登录重定向目标:', redirectTarget);
          // 清除重定向目标
          localStorage.removeItem('loginRedirect');
          
          // 检查用户角色和目标页面权限
          if (redirectTarget === '/create-project' && !this.isResearcher) {
            console.log('用户不是研究者，无法访问创建项目页面');
            this.$router.push('/');
          } else {
            // 执行重定向
            console.log('执行重定向到:', redirectTarget);
            this.$router.push(redirectTarget);
          }
        }
      } else {
        console.log('未检测到登录用户');
      }
    }, 500);
  },
  computed: {
    isLoggedIn() {
      return this.$store.getters['auth/isAuthenticated']
    },
    isResearcher() {
      return this.$store.getters['auth/isResearcher']
    },
    currentUser() {
      return this.$store.getters['auth/currentUser'] || {}
    },
    userName() {
      const user = this.currentUser;
      
      // 优先级顺序：username > fullName > name > userName > userId
      if (user.username) return user.username;
      if (user.fullName) return user.fullName;
      if (user.name) return user.name;
      if (user.userName) return user.userName;
      
      return user.id ? `用户${user.id}` : '未知用户';
    },
    userInitial() {
      const name = this.userName;
      return name && name !== '未知用户' ? name.charAt(0).toUpperCase() : '?';
    },
    userRoleText() {
      const user = this.currentUser;
      if (!user) return '';
      
      const role = user.role;
      // 根据注册表单中的角色定义，1是研究者，2是数据贡献者
      if (role === 1 || role === '1') return '研究者';
      if (role === 2 || role === '2') return '参与者';
      
      // 默认值
      return this.isResearcher ? '研究者' : '参与者';
    },
    userRoleClass() {
      return this.isResearcher ? 'role-researcher' : 'role-participant'
    }
  },
  methods: {
    async initUserData() {
      if (this.isLoggedIn && !this.userDataLoaded) {
        console.log('初始化用户数据');
        try {
          // 获取完整的用户信息（包括角色、姓名等）
          await this.$store.dispatch('auth/fetchUser');
          this.userDataLoaded = true;
          console.log('用户数据加载完成:', this.currentUser);
          
          // 如果仍然没有用户角色信息，尝试从token中解析或提示用户重新登录
          if (!this.currentUser || !this.currentUser.role) {
            console.warn('获取到的用户数据缺少角色信息，尝试从localStorage获取');
            // 从localStorage中获取用户数据
            const userData = JSON.parse(localStorage.getItem('user') || '{}');
            if (userData && userData.role) {
              console.log('从localStorage获取用户角色信息:', userData.role);
              // 更新用户信息
              this.$store.commit('auth/SET_USER', userData);
            } else {
              console.warn('无法获取有效的用户角色信息，可能需要重新登录');
            }
          }
        } catch (error) {
          console.error('获取用户数据失败:', error);
          // 处理错误，可能需要引导用户重新登录
          if (error.response && error.response.status === 401) {
            // token可能已过期
            this.$store.dispatch('auth/logout');
            this.$router.push('/login?expired=true');
          }
        }
      }
    },
    logout() {
      this.$store.dispatch('auth/logout');
      this.$router.push('/login');
      this.closeMobileMenu();
      this.userDataLoaded = false;
    },
    toggleMobileMenu() {
      this.mobileMenuActive = !this.mobileMenuActive;
      // 阻止滚动
      if (this.mobileMenuActive) {
        document.body.style.overflow = 'hidden';
      } else {
        document.body.style.overflow = '';
      }
    },
    closeMobileMenu() {
      this.mobileMenuActive = false;
      document.body.style.overflow = '';
    }
  },
  // 监听路由变化，确保在路由变化时也检查用户信息
  watch: {
    $route() {
      // 当路由变化时，确保用户数据已加载
      this.initUserData();
    }
  }
}
</script>

<style>
:root {
  --color-primary: #0055A4;
  --color-primary-light: #2D7CC5;
  --color-primary-dark: #003B72;
  --color-accent: #4CAF50;
  --color-accent-light: #6ABF6E;
  --color-accent-dark: #3B9F3E;
  --color-error: #E63946;
  --color-light: #fff;
  --color-dark: #243252;
  --color-medical-blue: #0055A4;
  --color-medical-light-blue: #E1F5FE;
}

#app {
  font-family: 'Inter', system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin: 0;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

body {
  margin: 0;
  padding: 0;
}

/* 导航栏样式 */
header {
  background-color: var(--color-light);
  box-shadow: 0 3px 10px rgba(0, 85, 164, 0.15);
  padding: 0;
  position: sticky;
  top: 0;
  z-index: 1000;
  border-bottom: 1px solid rgba(0, 85, 164, 0.1);
}

.header-container {
  max-width: 1440px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 70px;
}

.logo {
  display: flex;
  align-items: center;
}

.logo a {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: var(--color-medical-blue);
  font-weight: 800;
  font-size: 1.5rem;
}

.logo-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: var(--color-medical-blue);
  color: var(--color-light);
  border-radius: 8px;
  margin-right: 10px;
  font-size: 20px;
  font-weight: 900;
}

.logo-text {
  background: linear-gradient(45deg, var(--color-medical-blue), var(--color-primary-light));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

nav {
  display: flex;
  align-items: center;
}

.nav-link {
  font-weight: 600;
  color: var(--color-dark);
  margin: 0 15px;
  text-decoration: none;
  transition: all 0.3s;
  position: relative;
  padding: 8px 0;
}

.nav-link::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 3px;
  background: linear-gradient(90deg, var(--color-medical-blue), var(--color-primary-light));
  transition: width 0.3s ease;
  border-radius: 3px;
}

.nav-link:hover {
  color: var(--color-medical-blue);
}

.nav-link:hover::after,
.nav-link.router-link-exact-active::after {
  width: 100%;
}

.nav-link.router-link-exact-active {
  color: var(--color-medical-blue);
}

.logout-link {
  background-color: rgba(230, 57, 70, 0.1);
  color: var(--color-error);
  padding: 8px 15px;
  border-radius: 6px;
  transition: all 0.3s;
}

.logout-link:hover {
  background-color: var(--color-error);
  color: white;
}

.logout-link::after {
  display: none;
}

/* 移动端菜单 */
.mobile-menu-toggle {
  display: none;
  flex-direction: column;
  justify-content: space-between;
  width: 30px;
  height: 21px;
  cursor: pointer;
}

.bar {
  width: 100%;
  height: 3px;
  background-color: var(--color-medical-blue);
  border-radius: 3px;
  transition: all 0.3s;
}

.mobile-menu {
  display: none;
  position: fixed;
  top: 70px;
  left: 0;
  right: 0;
  background-color: var(--color-light);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 20px;
  flex-direction: column;
  transform: translateY(-100%);
  opacity: 0;
  transition: all 0.3s ease;
  z-index: 999;
  max-height: calc(100vh - 70px);
  overflow-y: auto;
}

.mobile-menu.active {
  transform: translateY(0);
  opacity: 1;
}

.mobile-nav-link {
  padding: 15px 0;
  font-weight: 600;
  color: var(--color-dark);
  text-decoration: none;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  display: block;
}

.mobile-nav-link:hover,
.mobile-nav-link.router-link-exact-active {
  color: var(--color-medical-blue);
  padding-left: 10px;
}

/* 响应式设计 */
@media (max-width: 900px) {
  nav {
    display: none;
  }
  
  .mobile-menu-toggle {
    display: flex;
  }
  
  .mobile-menu {
    display: flex;
  }
  
  .header-container {
    height: 60px;
  }
}

main {
  flex: 1;
  padding: 0;
}

footer {
  padding: 20px;
  background-color: var(--color-medical-light-blue);
  text-align: center;
  margin-top: 0;
  border-top: 1px solid rgba(0, 85, 164, 0.1);
  color: var(--color-medical-blue);
  font-weight: 500;
}

/* 用户身份样式 */
.user-identity {
  display: flex;
  align-items: center;
  margin: 0 15px;
  padding: 6px 10px;
  background-color: rgba(0, 85, 164, 0.05);
  border-radius: 20px;
  transition: all 0.3s;
}

.user-identity:hover {
  background-color: rgba(0, 85, 164, 0.1);
}

.user-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background-color: var(--color-primary);
  color: white;
  border-radius: 50%;
  font-weight: 600;
  margin-right: 10px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 600;
  color: var(--color-dark);
  line-height: 1.2;
}

.user-role {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.role-researcher {
  color: var(--color-primary);
}

.role-participant {
  color: var(--color-accent);
}

.user-role i {
  font-size: 12px;
}

/* 移动端用户身份 */
.mobile-user-identity {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #f8f9fa;
  margin: 5px 0;
}

@media (max-width: 768px) {
  .user-identity {
    display: none;
  }
}

.create-project-link {
  background-color: rgba(46, 204, 113, 0.1);
  color: #2ecc71;
  padding: 6px 12px;
  border-radius: 4px;
  margin-left: 5px;
  font-weight: 600;
}

.create-project-link:hover {
  background-color: #2ecc71;
  color: white;
}
</style> 